package com.bootmybatisdemo.demo.controller;

import com.bootmybatisdemo.demo.config.Global;
import com.bootmybatisdemo.demo.result.AjaxResult;
import com.bootmybatisdemo.demo.utils.FileUtils;
import com.bootmybatisdemo.demo.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.unit.DataSize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: 朱雄
 * Date: 2021/05/14 16:03
 * Description:文件上传
 * Version: V1.0
 */
@Slf4j
@RestController
public class FileUpload {

    @Value("${file.uploadFolder}")
    private String uploadFolder;


    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile[] file){
        String[] src=new String[file.length];
        for (int i=0;i<file.length;i++) {
            if (!file[i].isEmpty()) {
                Date date=new Date();
                int year=date.getYear()+1900;
                int month=date.getMonth()+1;
                int day=date.getDate();
                String uploadPath = uploadFolder+File.separator+year+File.separator+month+File.separator+day+File.separator;
                String fileName = file[i].getOriginalFilename();
                String ext=fileName.substring(fileName.lastIndexOf("."),fileName.length());
                File newFile = new File(uploadPath);
                //没有目录就创建
                if (!newFile.exists()) {
                    newFile.mkdirs();
                }
                String newFileName= UUID.randomUUID()+ext;
                File upNewFile = new File(uploadPath + newFileName);
                try {
                    file[i].transferTo(upNewFile);
                }catch (IOException e) {
                    return AjaxResult.error("文件上传失败");
                }
                String str=getUrl()+ File.separator+"upload"+File.separator+year+File.separator+month+File.separator+day+File.separator+newFileName;
                src[i]=str.replace("\\","/");
                System.out.println("upNewFile=" + str.replace("\\","/"));
            }
        }
        return AjaxResult.apisuccess("成功",StringUtils.join(src,","));
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = Global.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }


    public String getUrl()
    {
        HttpServletRequest request = getRequest();
        return getDomain(request);
    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }
    /**
     * 获取request
     */
    public static HttpServletRequest getRequest()
    {
        return getRequestAttributes().getRequest();
    }

    public static ServletRequestAttributes getRequestAttributes()
    {
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        return (ServletRequestAttributes) attributes;
    }
}

